<template>
  <div>
    <div v-if="items.length > 1">
      <div ref="swContentOut" class="swiper-container swiper-container-cp-swiper">
        <div class="swiper-wrapper">
          <div v-for="(item, index) in items" :key="index" class="swiper-slide">
            <slot name="item" :item="item" :index="index" />
          </div>
        </div>
        <slot name="pagination" />
      </div>
      <slot name="navigationPrev" />
      <slot name="navigationNext" />
    </div>
    <div v-else>
      <slot name="item" :item="items[0]" />
    </div>
  </div>
</template>

<script>
import Swiper from 'swiper/dist/js/swiper.min.js'

export default {
  props: {
    items: {
      type: Array,
      required: true
    },
    options: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      swiper: {}
    }
  },
  watch: {
    items: function(val) {
      if (val) {
        this.$nextTick(() => {
          this.swiper.destroy()
          this.swiper = new Swiper(this.$refs.swContentOut, this.returnWeOpt())
        })
      }
    }
  },
  mounted() {
    this.$nextTick(function() {
      this.swiper = new Swiper(this.$refs.swContentOut, this.returnWeOpt())
    })
  },
  methods: {
    returnWeOpt() {
      const _Vm = this
      const pagination = this.$slots.pagination
      const navigationPrev = this.$slots.navigationPrev
      const navigationNext = this.$slots.navigationNext
      let weOpt = {
        // observer:true,//修改swiper自己或子元素时，自动初始化swiper
        // observeParents:true//修改swiper的父元素时，自动初始化swiper
        // autoHeight: true,
        // noSwiping: true,
        on: {
          slideChangeTransitionStart: function() {
            _Vm.$emit('slideChangeTransitionEnd', this.activeIndex)
          }
        }
      }
      if (pagination) {
        weOpt = {
          ...weOpt,
          pagination: {
            clickable: true,
            el: pagination[0].elm
          }
        }
      }

      if (navigationPrev) {
        weOpt = {
          ...weOpt,
          navigation: {
            ...weOpt.navigation,
            prevEl: navigationPrev[0].elm
          }
        }
      }
      if (navigationNext) {
        weOpt = {
          ...weOpt,
          navigation: {
            ...weOpt.navigation,
            nextEl: navigationNext[0].elm
          }
        }
      }
      if (this.options) {
        weOpt = {
          ...weOpt,
          ...this.options,
          pagination: {
            ...weOpt.pagination,
            ...this.options.pagination
          },
          navigation: {
            ...weOpt.navigation,
            ...this.options.navigation
          },
          on: {
            ...this.options.on
          }
        }
      }
      return weOpt
    }
  }
}
</script>
